package com.v.im.gatewayservice.filter;

import com.alibaba.fastjson.JSONObject;
import com.v.im.commonmodule.utils.bean.CurrentUserInfo;
import com.v.im.commonmodule.utils.utils.UserHeaderUtil;
import com.v.im.gatewayservice.service.UserAuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器
 */
@Slf4j
@Component
public class MyTokenFilter implements GlobalFilter, Ordered {

    private final static String OAUTH_PATH = "/oauth/token";
    private final static String REGISTER_PATH = "/register";

    @Autowired
    private UserAuthService userAuthService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getPath().pathWithinApplication().value();
        //不拦截
        if (url.contains(OAUTH_PATH) || url.contains(REGISTER_PATH)) {
            return chain.filter(exchange);
        }
        String token = userAuthService.getTokenValue(exchange);
        if (StringUtils.isBlank(token)) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        ServerWebExchange build = exchange.mutate().build();
        CurrentUserInfo userInfo = userAuthService.getUserInfoByAuth(token);
        if (userInfo != null && userInfo.getUserId() != null) {
            //向headers中放文件，记得build
            String user = JSONObject.toJSONString(userInfo);
            ServerHttpRequest host = exchange.getRequest().mutate().header(UserHeaderUtil.CURRENT_USER_INFO, user).build();
            //将现在的request 变成 change对象
            build = exchange.mutate().request(host).build();
        }
        return chain.filter(build);
    }


    @Override
    public int getOrder() {
        return -100;
    }


}
